<?php
/**
 * @Author: Thans
 * @Date:   2018-09-20 00:06:10
 * @Last Modified by:   Thans
 * @Last Modified time: 2018-09-20 00:06:43
 */

namespace app\admin\service;

use app\common\model\UploadFileModel;

class UploadFileService
{
    //删除
    public function deletesByDId($ids)
    {
        $uid = cmf_get_uid();
        $res = UploadFileModel::where('d_id', 'in', $ids)->where('uid', $uid)->delete();
        //暂时不做 删除具体文件。
        if ($res) {
            return ['code' => 1001, 'data' => '', 'msg' => '删除成功'];
        } else {
            return ['code' => 4001, 'data' => '', 'msg' => '删除失败'];
        }
    }

    public function moveByDId($ids = array(), $gid = '')
    {
        $uid = cmf_get_uid();
        if (empty($ids)) {
            return ['code' => 4001, 'data' => '', 'msg' => '请选择要移动的文件'];
        }
        if (!$gid) {
            return ['code' => 4001, 'data' => '', 'msg' => '请选择目标分组'];
        }
        $res = UploadFileModel::where('d_id', 'in', $ids)->where('uid', $uid)->setField('gid', $gid);
        if ($res) {
            return ['code' => 1001, 'data' => '', 'msg' => '移动成功'];
        } else {
            return ['code' => 4001, 'data' => '', 'msg' => '移动失败'];
        }
    }

    public function getList($page = 1, $limit = 10, $type = 'image', $group = '-1')
    {
        $uid = cmf_get_uid();
        if ($group <= 0) {
            $map['uid'] = $uid;
            $map['file_type'] = $type;
            if ($group == 0) {
                $map['gid'] = 0;
            }
            $upload = UploadFileModel::where($map)
                ->order('id desc');
            $total = clone $upload;
            $res = $upload->page($page, $limit)->select();
            $res = $this->formatImageList($res);
            $total = $total->count();
            return ['code' => 1001, 'data' => $res, 'msg' => '获取成功', 'total' => $total];
        }
        $map['up.uid'] = $uid;
        $map['ug.uid'] = $uid;
        $map['ug.type'] = $type;
        $map['up.gid'] = $group;
        $upload = UploadFileModel::where($map)
            ->alias('up')
            ->join('upload_group ug', 'up.gid = ug.id', 'inner')
            ->order('up.id desc')
            ->field('up.*');
        $total = clone $upload;
        $res = $upload->page($page, $limit)
            ->select();
        $res = $this->formatImageList($res);
        $total = $total->count();
        return ['code' => 1001, 'data' => $res, 'msg' => '获取成功', 'total' => $total];
    }

    public function formatImageList($data)
    {
        foreach ($data as &$val) {
            $val['file_path_preview'] = cmf_get_image_url($val['file_path']);
        }
        return $data;
    }

    public function getById($id)
    {
        $file = UploadFileModel::get($id);
        return ['code' => 1001, 'data' => $file, 'msg' => '获取成功'];
    }

}
